import cv2 as cv
from PIL import Image, ImageDraw, ImageFont
import numpy as np


def cv2AddChineseText(img, text, position, color=(0, 0, 255), size=15):
    if isinstance(img, np.ndarray):  # 判断是否OpenCV图片类型
        img = Image.fromarray(cv.cvtColor(img, cv.COLOR_BGR2RGB))
    # 创建一个可以在给定图像上绘图的对象
    draw = ImageDraw.Draw(img)
    # 字体的格式
    style = ImageFont.truetype(
        "./simsun.ttc", size, encoding="utf-8")
    # 绘制文本
    draw.text(position, text, color, font=style)
    # 转换回OpenCV格式
    return cv.cvtColor(np.asarray(img), cv.COLOR_RGB2BGR)